#include "history.h"
#include "ui_history.h"
#include "qmqtt.h"
#include <QVector>
#include <QTimer>
#include <QTime>
#include <QDateTime>

#define TOPIC_DATA_UP       "/app/data/up"//数据接收up modbus
#define TOPIC_DATA_DOWN     "/app/data/down"//命令控制down
#define TOPIC_CTL_UP        "/app/control/up"//数据接收up stm32
#define TOPIC_CTL_DOWN      "/app/control/down"//命令控制down

//设置背景图片
void History::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    QPixmap pix(":/new/prefix2/picture_tubiao/beijing2.png");
    painter.drawPixmap(0, 0, pix);
}

History::History(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::History)
{
    ui->setupUi(this);

    // 手动调用槽函数刷新时间
    timeoutSlot();

    setupRealtimeDataDemo(ui->customPlot);
    ui->customPlot->replot();

    connect(ui->pushButton_temper,SIGNAL(clicked()),
            this,SLOT(btnwenduhistorySlot()));

    connect(ui->pushButton_shidu,SIGNAL(clicked()),
            this,SLOT(btnshiduhistorySlot()));

    run();
}

void History::run()
{
    //显示日期
    timer = new QTimer(this); // 创建定时器对象
    timer->setSingleShot(false); // 设置为周期性
    timer->setInterval(1000); // 设置间隔时间1000ms
    connect(timer,SIGNAL(timeout()),this,SLOT(timeoutSlot()));
    timer->start(); // 启动定时器
}

void History::timeoutSlot()
{

    // 获得当前时间
    QDateTime dt = QDateTime::currentDateTime();
    // 格式化
    QString text = dt.toString("yyyy-MM-dd hh:mm:ss");
    // 设置显示
    //ui->lcdNumber->display(text);
}


History::~History()
{
    delete ui;
}

void History::publish(QByteArray text)
{
    QMQTT::Message message;
    message.setTopic(TOPIC_DATA_DOWN);//确定下发数据的主题
    message.setPayload(text);

    qDebug() << "topic:" <<message.topic();
    qDebug() << "payload:"<<message.payload();

    emit dataDownSignal(message);
}

void History::dataUpSlot(const QByteArray & json)
{
    qDebug()<<"history处理解析json语句";
    QJsonParseError jsonerror;//报告 JSON 处理过程中出现的错误
    //将json解析为utf-8的QJSON文档（读写 JSON 文档）
    QJsonDocument doucment = QJsonDocument::fromJson(json,&jsonerror);
    //判断文档是否有效性
    if (!doucment.isNull() && (jsonerror.error == QJsonParseError::NoError))
    {
        //查询一个文档是否包含了一个object
        if(doucment.isObject())
        {
            QJsonObject object = doucment.object();//封装对象
            if(object.contains("type")&&object.contains("result"))
            {
                int type = object.value("type").toInt();
                qDebug()<<"type: "<< type;
                if(object.contains("key"))//解析key的值
                {
                    int key = object.value("key").toInt();
                    QJsonValue value= object.value("data");
                    if(value.isArray())
                    {
                        QJsonArray array = value.toArray();
                        for(int i = 0; i < array.size(); i++)
                        {
                            //遍历数组
                            QJsonValue value = array.at(i);
                            if(value.isObject())
                            {
                                object = value.toObject();
                                QString val = object.value("val").toString();
                                qint64 time = object.value("time").toInt();

                                if(key == 3011)//温度
                                {
                                    double val_temper = val.toDouble();
                                    temper.append(val_temper);
                                    time_temper.append(time);
                                }
                                else if(key==3012)//湿度
                                {
                                    double val_shidu = val.toDouble();
                                    shidu.append(val_shidu);
                                    time_shidu.append(time);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    emit SelectSignal();
}

void History::realtimeDataSlot()
{
    qDebug()<<"进入槽函数";
    for(int i=0;i<time_temper.size();i++)
    {
        //依次获取vector中的时间和温度的数值
        double key = time_temper.at(i);
        double value0 = temper.at(i);

        //qDebug()<<"这是温度的key值"<<key<<value0;

        ui->customPlot->graph(0)->addData(key, value0);//添加数据1到曲线1

        //ui->customPlot->graph(0)->removeDataBefore(key-60);
        // ui->customPlot->graph(1)->removeDataBefore(key-60);

        ui->customPlot->yAxis->setRange(10,50);//手动设定y轴范围
        //对第一个曲线的 y 轴进行重新缩放，以适应数据范围。
        ui->customPlot->graph(0)->rescaleValueAxis();
        //对第二个曲线的 y 轴进行重新缩放，通过传递 true 参数，确保两个曲线共享相同的 y 轴范围。
        ui->customPlot->graph(1)->rescaleValueAxis(true);

        //对x轴范围进行设置，key是x轴的起始范围，60是范围长度
        ui->customPlot->xAxis->setRange(key, 10, Qt::AlignRight);
        //重新绘制图表
        ui->customPlot->replot();


    }
    for(int i=0;i<time_shidu.size();i++)
    {
        double key = time_shidu.at(i);
        double value1 = shidu.at(i);

        ui->customPlot->graph(1)->addData(key, value1);//添加数据2到曲线2

        //ui->customPlot->graph(0)->removeDataBefore(key-60);
        //ui->customPlot->graph(1)->removeDataBefore(key-60);

        ui->customPlot->yAxis->setRange(30,10);//手动设定y轴范围
        ui->customPlot->graph(0)->rescaleValueAxis();
        ui->customPlot->graph(1)->rescaleValueAxis(true);

        ui->customPlot->xAxis->setRange(key, 15, Qt::AlignRight);//设定x轴的范围
        ui->customPlot->replot();
    }
}

void History::btnwenduhistorySlot()
{
    //qDebug()<<"进入了温度的槽函数";
    QJsonObject json;//创建一个空的 QJsonObject 对象,封装json对象
    QJsonDocument document;//读写json文档
    //当前时间戳
    qint64 startTime = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;
    qint64 endTime  = startTime-100;

    //创建limit数组对象
    QJsonArray limitArray;
    limitArray.append(endTime);
    limitArray.append(startTime);

    //创建data对象
    QJsonObject data;
    data.insert("key",3011);
    data.insert("limit",limitArray);
    //创建根对象
    json.insert("type",4);
    json.insert("data",QJsonObject(data));

    document.setObject(json);//构建json对象
    QByteArray byte_arry = document.toJson(QJsonDocument::Compact);
    qDebug()<<"温度查询完毕";
    publish(byte_arry);
}

void History::btnshiduhistorySlot()
{
    QJsonObject json;//创建一个空的 QJsonObject 对象,封装json对象
    QJsonDocument document;//读写json文档

    //当前时间戳
    qint64 startTime = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;
    //qDebug()<< "这是当前时间:"<< timeTemp;
    qint64 endTime  = startTime-100;

    //创建limit数组对象
    QJsonArray limitArray;
    limitArray.append(endTime);
    limitArray.append(startTime);

    //创建data对象
    QJsonObject data;
    data.insert("key",3012);
    data.insert("limit",limitArray);
    //创建根对象
    json.insert("type",4);
    json.insert("data",QJsonObject(data));

    document.setObject(json);//构建json对象
    QByteArray byte_arry = document.toJson(QJsonDocument::Compact);
    //qDebug()<<"湿度查询完毕";
    publish(byte_arry);
}



void History::setupRealtimeDataDemo(QCustomPlot *customPlot)
{
    customPlot->setNotAntialiasedElements(QCP::aeAll);

    QFont font;
    font.setStyleStrategy(QFont::NoAntialias);
    customPlot->xAxis->setTickLabelFont(font);
    customPlot->yAxis->setTickLabelFont(font);
    customPlot->legend->setFont(font);

    customPlot->addGraph();
    customPlot->graph(0)->setPen(QPen(Qt::blue));//线条颜色
    customPlot->graph(0)->setName("temp");

    customPlot->addGraph();
    customPlot->graph(1)->setPen(QPen(Qt::red));
    customPlot->graph(1)->setName("hui");

    customPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime);
    customPlot->xAxis->setDateTimeFormat("hh:mm:ss");
    customPlot->xAxis->setAutoTickStep(false);
    customPlot->xAxis->setTickStep(2);
    customPlot->axisRect()->setupFullAxesBox();

    connect(this,SIGNAL(SelectSignal()),this,SLOT(realtimeDataSlot()));
    customPlot->legend->setVisible(true);
}
